﻿package com.winfield.photovideo;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.winfield.utils.MyNetWork;

/**
 * 该类用于预览资源  显示资源预览的窗口
 * 需要引入的jar包有三个  分别是library 、PullToRefreshListFragment、PullToRefreshViewPager
 * @author zsh
 *
 */
public final class PreSrcActivity extends ListActivity {

	private LinkedList<String> mListItems;
	private PullToRefreshListView mPullRefreshListView;
//	private ArrayAdapter<String> mAdapter;
//	private SimpleAdapter adapter;
	private MyAdapter myAdapter;//自定义适配器
	ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();//适配器数据容器
	private int para=0;
	private String userID ;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		
	    //intent是用于激活它的对象
	    Intent intent = getIntent();
        //获取userID
        Bundle bundle = intent.getExtras();
		userID = bundle.getString("userID");
		
		
		

		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {//下拉刷新监听器
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				new GetDataTask().execute();//下拉时异步刷新数据

			}
		});
		mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {//拉到底部时触发事件
			
			@Override
			public void onLastItemVisible() {
				Toast.makeText(PreSrcActivity.this, "End of List!", Toast.LENGTH_SHORT).show();
			}
		});

		ListView actualListView = mPullRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);


		getDataList();//第一次获取数据

		myAdapter = new MyAdapter(this, list);//适配器填数据
		actualListView.setAdapter(myAdapter);
	}

    private void getDataList(){  
    	try {
    		//String jsonStr = doPost(null, "http://192.168.155.1/web/php/SourcesPreview.php?para="+para+"&userid="+userID);
    		String jsonStr = doPost(null, MyNetWork.PVAPPWEB_P+"SourcesPreview.php?para="+para+"&userid="+userID);
    		
			Analysis(jsonStr);//解析json并刷新适配器数据
			para+=2;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}

    } 
   
	private class GetDataTask extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {

		@Override
		protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
			try {
				Thread.sleep(4000);
			} catch (InterruptedException e) {
			}
			return list;
		}

		@Override
		protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
	        HashMap<String, String> map = new HashMap<String, String>();  
	        getDataList();
	        
	        myAdapter.notifyDataSetChanged();

			mPullRefreshListView.onRefreshComplete();

			super.onPostExecute(result);
		}
	}
	
	/**
     * 访问数据库并返回JSON数据字符串
     * 
     * @param params 向服务器端传的参数
     * @param url
     * @return
     * @throws Exception
     */
    public String doPost(List<NameValuePair> params, String url)throws Exception {
        String result = null;// 获取HttpClient对象
        HttpClient httpClient = new DefaultHttpClient();// 新建HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        if (params != null) {
            HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);// 设置字符集
            httpPost.setEntity(entity);// 设置参数实体
        }

        HttpResponse httpResp = httpClient.execute(httpPost);
        if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
        } else {
            Log.e("HttpPost", "HttpPost方式请求失败");
        }
        return result;
    }
    
    /**
     * 解析
     * 
     * @throws JSONException
     */
    private void Analysis(String jsonStr) throws JSONException {
        /******************* 解析 ***********************/
        JSONArray jsonArray = null;
        //ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();// 初始化list数组对象
        jsonArray = new JSONArray(jsonStr);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            HashMap<String, String> map = new HashMap<String, String>();// 初始化map数组对象
            map.put("username", jsonObject.getString("username"));
            map.put("time", jsonObject.getString("pvtime"));
            map.put("url", jsonObject.getString("filethupath")+"/"+jsonObject.getString("filethuname"));
            this.list.add(map);
        }
    }

    class MyAdapter extends BaseAdapter{//自定义适配器  主要重写getView方法  在这里处理数据

        private ArrayList<HashMap<String, String>> list;  
        Context context;  
          
        public class ViewHolder{  
            TextView title;  
            TextView time;  
            ImageView imageView;  
        } 
        
        public MyAdapter(Context context,ArrayList<HashMap<String, String>> list){  
            this.list = list;  
            this.context = context;  
        }  
        
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {  
//		        final Person person = (Person)getItem(position);  
				HashMap<String, String> map = (HashMap<String, String>)getItem(position);
		        ViewHolder viewHolder = null;  
		        if(convertView==null){    
		            convertView = LayoutInflater.from(context).inflate(  
		                    R.layout.listitem, null);  
		              
		            viewHolder = new ViewHolder();  
		            viewHolder.title = (TextView)convertView.findViewById(  
		                    R.id.title);  
		            viewHolder.time = (TextView)convertView.findViewById(  
		                    R.id.time);   
		            viewHolder.imageView = (ImageView)convertView.findViewById(R.id.image); 
		            convertView.setTag(viewHolder);  
		        }else{  
		            viewHolder = (ViewHolder)convertView.getTag();  
		            Log.d("MyBaseAdapter", "旧的convertView,position="+position);  
		        }  
		        viewHolder.title.setText((String)map.get("username"));  
		        viewHolder.time.setText((String)map.get("time"));
		        Bitmap bitmap = null;  
		        try  
		        {  
		            URL url = new URL((String)map.get("url"));  
		            bitmap = BitmapFactory.decodeStream(url.openStream());  
		        } catch (Exception e)  
		        {  
		            // TODO Auto-generated catch block  
		            e.printStackTrace();  
		        }  
		        viewHolder.imageView.setImageBitmap(bitmap); 
  
		          


		          
		        return convertView;  
		    }  
    	
    }

}
